<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品计划</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .submenu { display: none; }
        .menu-item.active > .submenu { display: block; }
        .menu-arrow { transition: transform 0.2s; }
        .menu-item.active > a > .menu-arrow { transform: rotate(90deg); }
        .table th { background-color: #f8f9fa; }
        .submenu li a.active { color: #28a745; font-weight: bold; transform: translateY(2px); display: inline-block; }
        .search-area { background: #f8f9fa; padding: 10px; border-radius: 8px; margin: 10px 0; width: 100%; }
        .search-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .search-item { flex: 0 0 auto; margin-right: 10px; margin-bottom: 5px; }
        .search-item .form-control, .search-item .form-select { width: 120px; height: 31px; font-size: 14px; }
        .search-item .btn { padding: 4px 8px; }
        .search-label { display: block; margin-bottom: 5px; font-size: 14px; color: #555; white-space: nowrap; }
        .table-responsive { overflow-x: auto; margin: 0 -20px; padding: 0 20px; }
        .custom-table { width: 100%; border-collapse: separate; border-spacing: 0; }
        .custom-table th { background: #f8f9fa; color: #495057; font-weight: 600; padding: 12px 15px; border-bottom: 2px solid #dee2e6; white-space: nowrap; }
        .custom-table td { padding: 12px 15px; border-bottom: 1px solid #eee; vertical-align: middle; }
        .action-buttons { display: flex; gap: 8px; }
        .action-buttons .btn {
            padding: 4px 10px;
            font-size: 13px;
            min-width: 60px;
            white-space: nowrap;
        }
        .page-title { font-size: 22px; font-weight: 600; margin-bottom: 20px; color: #333; display: flex; align-items: center; gap: 10px; }
        .page-title-icon { font-size: 24px; }
        .ms-auto { margin-left: auto; }
        .add-button { padding: 8px 16px; display: flex; align-items: center; gap: 5px; font-weight: 500; }
        .content-wrapper { padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 20px; }
        .detail-item {
            margin-bottom: 15px;
        }
        .detail-label {
            font-weight: 600;
            color: #495057;
            margin-right: 10px;
        }
        .modal-lg {
            max-width: 800px;
        }
        /* iOS风格模态框样式 */
        .ios-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1050;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .ios-modal.show {
            display: flex;
            opacity: 1;
        }

        .ios-modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 0;
            max-width: 400px;
            width: 90%;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }

        .ios-modal.show .ios-modal-content {
            transform: scale(1);
        }

        .ios-modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .ios-modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .ios-modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .ios-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .ios-detail-item:last-child {
            border-bottom: none;
        }

        .ios-detail-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
        }

        .ios-detail-value {
            font-weight: 400;
            color: #333;
            font-size: 14px;
            text-align: right;
            max-width: 60%;
            word-wrap: break-word;
        }

        .ios-modal-footer {
            padding: 15px 20px 20px;
            text-align: center;
        }

        .ios-close-btn {
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .ios-close-btn:hover {
            background: #0056CC;
        }

        /* 滚动条样式 */
        .ios-modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .ios-modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .ios-modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }
        /* 重置默认样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f7f7f7;
            color: #333;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
        }

        /* 顶部导航栏 */
        .admin-header {
            background-color: #ffffff;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            height: 56px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 100;
        }

        .admin-header .logo {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .admin-header .header-right {
            display: flex;
            align-items: center;
        }

        .admin-header .user-info {
            margin-right: 20px;
            color: #555;
        }

        .admin-header .logout-btn {
            color: #555;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 4px;
        }

        .admin-header .logout-btn:hover {
            background-color: #f8f9fa;
        }

        /* 主要内容布局 */
        .admin-layout {
            display: flex;
            height: 100vh;
            padding-top: 56px; /* 为固定的顶部栏留出空间 */
        }

        /* 侧边栏 - 紧贴顶部栏 */
        .admin-sidebar {
            width: 240px;
            background-color: #ffffff;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            position: sticky;
            top: 56px;
            height: calc(100vh - 56px);
            overflow-y: auto;
            z-index: 90;
        }

        .menu-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .menu-item > a {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 20px;
            color: #333;
            text-decoration: none;
            cursor: pointer;
        }

        .menu-item > a:hover {
            background-color: #f8f9fa;
        }

        .menu-item.active > a {
            background-color: #e8f5e9;
            color: #28a745;
        }

        .submenu {
            list-style: none;
            padding: 0;
            margin: 0;
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .submenu li a {
            display: block;
            padding: 10px 20px 10px 40px;
            color: #555;
            text-decoration: none;
        }

        .submenu li a:hover {
            background-color: #f8f9fa;
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: 600;
        }

        .menu-arrow {
            transition: transform 0.2s;
            font-size: 10px;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            margin-left: -20px; /* 为侧边栏留出空间 */
            padding: 20px;
            overflow-y: auto;
        }

        .content-wrapper {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            padding: 24px;
            max-width: 95%; /* 增加主内容区域宽度 */
            margin: 0 auto;
        }

        .content-header {
            margin-bottom: 24px;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 16px;
        }

        #pageTitle {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        /* iOS风格表单 */
        .form-container {
            max-width: 100%;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #666;
            margin-bottom: 8px;
            display: block;
        }

        .required-field::after {
            content: "*";
            color: #dc3545;
            margin-left: 4px;
        }

        .form-control, .form-select {
            height: 44px;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 0 16px;
            font-size: 16px;
            transition: all 0.2s ease;
            width: 100%;
            background-color: #f9f9f9;
        }

        .form-control:focus, .form-select:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
            background-color: #fff;
            outline: none;
        }

        /* 按钮样式 */
        .btn {
            height: 44px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            padding: 0 20px;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: #28a745;
            border-color: #28a745;
        }

        .btn-primary:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }

        .btn-secondary {
            background-color: #f2f2f7;
            border-color: #f2f2f7;
            color: #28a745;
        }

        .btn-secondary:hover {
            background-color: #e5e5ea;
            border-color: #e5e5ea;
        }

        .btn-action {
            min-width: 120px;
        }

        /* 表格样式 - 增加列间距 */
        .table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 12px; /* 增加行间距 */
        }

        .table th, .table td {
            padding: 12px 16px; /* 增加单元格内边距 */
            vertical-align: middle;
            border-top: none;
        }

        .table thead th {
            border-bottom: 2px solid #e9ecef;
            font-weight: 600;
            background-color: #f8f9fa;
        }

        .table tbody tr {
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }

        .table tbody tr:hover {
            background-color: #f8f9fa;
        }

            
        /* 响应式调整 */
        @media (max-width: 768px) {
            .admin-sidebar {
                display: none;
                width: 240px;
                z-index: 99;
            }

            .admin-sidebar.active {
                display: block;
            }

            .main-content {
                margin-left: 0;
                padding: 10px;
            }

            .content-wrapper {
                padding: 16px;
                max-width: 100%;
            }

            .mobile-menu-button {
                display: flex;
                position: fixed;
                bottom: 20px;
                right: 20px;
                background-color: #28a745;
                color: white;
                width: 50px;
                height: 50px;
                border-radius: 50%;
                align-items: center;
                justify-content: center;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                z-index: 98;
            }

            /* 移动端表格样式优化 */
            .table {
                border-spacing: 0 8px;
            }

            .table th, .table td {
                padding: 8px 10px;
                font-size: 14px;
            }
        }

        @media (min-width: 769px) {
            .mobile-menu-button {
                display: none;
            }
        }
    </style>
</head>
<body class="bg-light text-dark font-sans">
<!-- 顶部导航栏 -->
<header class="admin-header">
    <div class="header-left">
        <div class="logo">生产过程管理系统</div>
    </div>
    <div class="header-right">
        <span class="user-info">管理员</span>
        <button class="logout-btn" onclick="logout()">退出</button>
    </div>
</header>
<div class="admin-layout">
    <aside class="admin-sidebar">
    <ul class="menu-list">
        <li class="menu-item">
            <a href="../homepage/manager_home.html">
                <span class="menu-icon">🏠</span>
                <span class="menu-title">首页</span>
            </a>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">👥</span>
                <span class="menu-title">人员管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../person/person_list.html">人员列表</a></li>
                <li><a href="../person/person_edit.html">添加人员</a></li>
                <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                <li><a href="../person/schedule.html">查看排班表</a></li>
                <li><a href="../person/schedule_statistics.html">班次统计</a></li>
            </ul>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">📦</span>
                <span class="menu-title">物料管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../material/material_list.html">物料列表</a></li>
                <li><a href="*">物料采购统计</a></li>
            </ul>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">⚙️</span>
                <span class="menu-title">设备管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../device/device_list.html">设备列表</a></li>
                <li><a href="*">设备报修报废统计</a></li>
            </ul>
        </li>
        <li class="menu-item active">
            <a href="javascript:void(0)">
                <span class="menu-icon">📝</span>
                <span class="menu-title">产品管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="product_list.html">产品列表</a></li>
                <li><a href="editproduct_plan.html" class="active">编辑产品计划</a></li>
                <li><a href="viewproduct_plan.html">查看产品计划</a></li>
            </ul>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">🏢</span>
                <span class="menu-title">供应商管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../provider/provider_list.html">供应商列表</a></li>
            </ul>
        </li>
    </ul>
</aside>
    <main class="main-content">
        <div class="content-wrapper">
            <div class="content-header">
                <h1 id="pageTitle">产品计划</h1>
            </div>

            <!-- 1. 开始和结束时间输入框 -->
            <div class="form-container">
                <div class="form-group">
                    <label for="start_time" class="form-label required-field">开始时间</label>
                    <input type="date" id="start_time" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="end_time" class="form-label required-field">结束时间</label>
                    <input type="date" id="end_time" class="form-control" required>
                </div>
            </div>

            <!-- 2. 产品列表表格 -->
            <div class="form-container">
                <h3>产品列表</h3>
                <table class="table">
                    <thead>
                    <tr>
                        <th>产品身份码</th>
                        <th>产品名称</th>
                        <th>外观尺寸</th>
                        <th>批次</th>
                        <th>加工人员</th>
                        <th>加工方法</th>
                        <th>加工时间</th>
                        <th>加工车间</th>
                        <th>数量</th>
                    </tr>
                    </thead>
                    <tbody id="product-table-body">
                    <!-- 数据将通过 JavaScript 动态插入 -->
                    </tbody>
                </table>
            </div>

            <!-- 3. 描述输入框 -->
            <div class="form-container">
                <div class="form-group">
                    <label for="description" class="form-label required-field">描述</label>
                    <textarea id="description" class="form-control" rows="3" required></textarea>
                </div>
            </div>

            <!-- 4. 提交按钮 -->
            <div class="form-container text-center">
                <button id="submit-btn" class="btn btn-primary btn-action">提交</button>
            </div>
        </div>
    </main>
</div>

<!-- 移动端菜单按钮 -->
<button id="mobileMenuBtn" class="mobile-menu-button">
    <i class="fa fa-bars text-xl"></i>
</button>

<script src="../../assets/bootstrap.bundle.min.js"></script>
<script>
    // 菜单展开/收起功能，完全同步product_list.html
    document.addEventListener('DOMContentLoaded', function () {
        // 菜单折叠功能
        var menuItems = document.querySelectorAll('.menu-item > a');
    menuItems.forEach(function (item) {
        item.addEventListener('click', function (e) {
            var parent = item.parentElement;
            // 判断是否为可展开的菜单（包含submenu的项）
            if (parent.querySelector('.submenu')) {
                // 只对可展开的菜单阻止默认行为
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');
                e.preventDefault();
            }
            // 对直接链接（如首页）不阻止默认行为，允许跳转
        });
    });

        // 默认展开产品管理菜单
        const productMenuItem = document.querySelector('.menu-item.active');
        if (productMenuItem) {
            productMenuItem.classList.add('active');
        }
        // 设置当前页面对应的菜单项为选中状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href') === filename) {
                link.classList.add('active');
            }
        });
        // 移动端菜单切换
        document.getElementById('mobileMenuBtn').addEventListener('click', function() {
            document.querySelector('.admin-sidebar').classList.toggle('active');
        });
    });

    // 获取URL中的plan_id参数
    const urlParams = new URLSearchParams(window.location.search);
    const planId = urlParams.get('plan_id');
    const isEditMode = !!planId;

    // 页面加载完成后获取产品数据
    document.addEventListener('DOMContentLoaded', function() {
        fetchProducts(planId);

        // 绑定提交按钮点击事件
        document.getElementById('submit-btn').addEventListener('click', function() {
            handleSubmit(planId);
        });
    });

    // 获取所有产品数据并显示在表格中，若有plan_id则填充已有数量
    async function fetchProducts(planId) {
        try {
            // 并行获取产品列表和计划详情
            const [productsResponse, detailsResponse] = await Promise.all([
                fetch('http://localhost:8080/api/products'),
                planId ? fetch(`http://localhost:8080/api/Product_Plan_Details/plan/${planId}`) : Promise.resolve(null)
            ]);

            const products = await productsResponse.json();
            const details = detailsResponse ? await detailsResponse.json() : [];

            // 将详情数据转换为以product_code为键的映射
            const detailMap = {};
            details.forEach(detail => {
                detailMap[detail.product_code] = detail.product_quantity;
            });

            const tableBody = document.getElementById('product-table-body');
            products.forEach(product => {
                const row = document.createElement('tr');
                // 从映射中获取数量，如果不存在则默认为0
                const quantity = detailMap[product.productCode] || 0;
                row.innerHTML = `
                    <td>${product.productCode}</td>
                    <td>${product.name}</td>
                    <td>${product.size}</td>
                    <td>${product.batch}</td>
                    <td>${product.operatorName}</td>
                    <td>${product.processMethod}</td>
                    <td>${product.processTime}</td>
                    <td>${product.workshop}</td>
                    <td>
                        <input type="number" value="${quantity}" min="0" class="form-control quantity-input" data-product-code="${product.productCode}">
                    </td>
                `;
                tableBody.appendChild(row);
            });

            // 如果有plan_id，获取并填充计划基本信息
            if (planId) {
                fetch(`http://localhost:8080/api/product_plans/${planId}`)
                    .then(response => response.json())
                    .then(plan => {
                        document.getElementById('start_time').value = plan.start_time;
                        document.getElementById('end_time').value = plan.end_time;
                        document.getElementById('description').value = plan.description;
                    })
                    .catch(error => console.error('获取计划信息失败:', error));
            }
        } catch (error) {
            console.error('获取产品数据时出错:', error);
        }
    }

    // 提交按钮点击事件 - 根据是否有plan_id决定是新增还是编辑
    async function handleSubmit(planId) {
        const start_time = document.getElementById('start_time').value;
        const end_time = document.getElementById('end_time').value;
        const description = document.getElementById('description').value;

        try {
            let planData;

            if (planId) {
                // 更新计划基本信息
                const response = await fetch(`http://localhost:8080/api/product_plans/${planId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ start_time, end_time, description })
                });

                if (!response.ok) {
                    throw new Error(`更新计划失败: ${await response.text()}`);
                }

                planData = { plan_id: planId };
            } else {
                // 创建新计划
                const response = await fetch('http://localhost:8080/api/product_plans', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ start_time, end_time, description })
                });

                if (!response.ok) {
                    throw new Error(`创建计划失败: ${await response.text()}`);
                }

                planData = await response.json();
            }

            const plan_id = planData.plan_id;
            const quantityInputs = document.querySelectorAll('.quantity-input');
            const newDetails = [];

            // 收集用户输入的产品数量
            quantityInputs.forEach(input => {
                const product_code = input.dataset.productCode;
                const quantity = parseInt(input.value);
                if (quantity > 0) {
                    newDetails.push({ plan_id, product_code, product_quantity: quantity });
                }
            });

            if (planId && newDetails.length > 0) {
                // 编辑模式：先获取现有明细
                const existingDetails = await fetch(`http://localhost:8080/api/Product_Plan_Details/plan/${planId}`)
                    .then(res => res.json());

                // 计算需要删除的明细（用户已将数量设为0的记录）
                const detailsToDelete = existingDetails
                    .filter(existing => !newDetails.some(newDetail =>
                        newDetail.product_code === existing.product_code
                    ));

                // 执行删除操作
                await Promise.all(detailsToDelete.map(detail =>
                    fetch(`http://localhost:8080/api/Product_Plan_Details/${detail.detail_id}`, { method: 'DELETE' })
                ));
            }

            // 插入或更新明细
            if (newDetails.length > 0) {
                const responses = await Promise.all(
                    newDetails.map(detail =>
                        fetch('http://localhost:8080/api/Product_Plan_Details', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(detail)
                        })
                    )
                );

                const allSuccess = responses.every(res => res.ok);
                if (!allSuccess) {
                    throw new Error('更新计划明细失败');
                }
            }

            alert('提交成功');
            window.location.href = 'viewproduct_plan.html';
        } catch (error) {
            console.error('提交时出错:', error);
            alert(`提交失败: ${error.message}`);
        }
    }

    // 退出登录
    function logout() {
        alert('退出登录');
        window.location.href = '../../login.html';
    }
</script>
</body>
</html>